/*
 * Copyright (c) 2006-2021, RT-Thread Development Team
 *
 * SPDX-License-Identifier: Apache-2.0
 * 用于Honeywell的压力传感器压力值读取
 * Change Logs:
 * Date           Author       Notes
 * 2021-07-25     wyjhotice    1.0.0
 */
////使用：1，需要修改相应的spi io口，
/// 2，需要使能相应的spi，注意使用cube 使能相应的io口
#include <rtthread.h>
#include <rtdevice.h>
#include <board.h>
#include "drv_spi.h"
#include "HONEYWELL_PRES_SPI/pres.h"

#define DBG_TAG "Honeywell"
#define DBG_LVL DBG_INFO
#include <rtdbg.h>

static struct rt_spi_device *spi_dev_honeywell;
static struct rt_spi_configuration spi_dev_honeywell_cfg;
static int honeywell_soner_init(void)
{

    HONEYWELL_SENSER_RCC_ENABLE
    ;

    rt_hw_spi_device_attach(HONEYWELL_SPI, HONEYWELL_SPI0, HONEYWELL_SENSER_CS_GPIO, HONEYWELL_SENSER_CS_PIN);
    //spi_dev_honeywell = (struct rt_spi_device *) rt_device_find(HONEYWELL_SPI0);
    spi_dev_honeywell = (struct rt_spi_device *) rt_device_find(HONEYWELL_SPI0);
    if(!spi_dev_honeywell)
    {
        LOG_E("honeywell sensor init failed!!can't find %s device!\n", HONEYWELL_SPI0);
    }
    spi_dev_honeywell_cfg.data_width = 8;
    spi_dev_honeywell_cfg.mode = RT_SPI_MASTER | RT_SPI_MODE_0 | RT_SPI_MSB;
    spi_dev_honeywell_cfg.max_hz = 800 * 1000; /* 500k */
    rt_spi_configure(spi_dev_honeywell, &spi_dev_honeywell_cfg);
    return RT_EOK;

}

INIT_APP_EXPORT(honeywell_soner_init);

int32_t get_pressure_and_temp(void)
{
    uint8_t pressure_temp[4];
    uint16_t re_value = 0;
    int32_t ret;
    long pres_or_temp_value = 0;
    rt_spi_recv(spi_dev_honeywell, pressure_temp, 4);
    //HAL_Delay(5);
    if ((pressure_temp[0] & 0xc0) == 0)
    {
        if (1) //(type == 0)               //取压力
        {
            re_value = (((uint16_t) pressure_temp[0]) << 8) | ((uint16_t) (pressure_temp[1]));
            re_value = re_value & 0x3fff;
            pres_or_temp_value = (re_value - 1638) * 160000 / 13107;

        }
        else                          //取温度
        {
            re_value = (((uint16_t) pressure_temp[2]) << 8) | ((uint16_t) (pressure_temp[3]));
            re_value = re_value >> 5;
            pres_or_temp_value = re_value * 2000 / 2047 - 500;

        }
        if (pres_or_temp_value == 0)
            pres_or_temp_value++;
        if (pres_or_temp_value & 0x80000000)
        {
            pres_or_temp_value = ~pres_or_temp_value;
            ret = pres_or_temp_value;
            ret = ~ret;
            LOG_D("pres value :%d\r\n",ret);
            return ret;
        }
        else
        {
            LOG_D("pres value :%d\r\n",ret);
            ret = pres_or_temp_value;
            return ret;
        }
    }
    else
        return 0;
}
MSH_CMD_EXPORT(get_pressure_and_temp, get_pressure_and_temp);
